// ==UserScript==
// @name           Yahoo Hockey Custom Standings
// @namespace      www.adlc.ca
// @description    Provides a Custom Standings Table for Yahoo Fantasy Hockey
// @include        http://hockey.fantasysports.yahoo.com/hockey/36753
// @include        http://hockey.fantasysports.yahoo.com/league/federal_league123
// @include        http://hockey.fantasysports.yahoo.com/2011/hockey/36753
// ==/UserScript==
//

var poolURL = "/hockey/36753";
/**
Create all the teams as an array of Team objects with an ID their rank from the
* previous season, for calculation of most improved.
*/
var teams = new Array();

teams["3"] =  new Team("3", "8");//Bucky Ski Pole Snipers
teams["6"] =  new Team("6", "7");//Brett Regina Shockers
teams["11"] =  new Team("11", "5");//Tim Puttin on the Foil
teams["1"] =  new Team("1", "2");//Alan Heatley Crashers
teams["8"] =  new Team("8", "11");//Trevor Hanson Express
teams["10"] =  new Team("10", "3");//Keenan Winds of Shit
teams["2"] =  new Team("2", "12");//Terry The Terrorizors
teams["7"] =  new Team("7", "6");//Greg Zidlicky my Balls
teams["12"] =  new Team("12", "10");//Mike trademerightfuckinnow
teams["5"] =  new Team("5", "1");//Josh Ogie Ogilthorpe
teams["9"] =  new Team("9", "9");//Kuzio Get ur done
teams["4"] =  new Team("4", "4");//Leibel Chizziwooger

/**
Member method of Team for calculating 2nd half points.
*/
function Team_getSecondHalfPoints() {
    return (this.firstHalfPoints == 0) ? 0 : this.totalPoints - this.firstHalfPoints;
}

function Team_getFirstHalfPoints() { return (this.firstHalfPoints == 0) ? this.totalPoints - this.getSecondHalfPoints() : this.firstHalfPoints; }

function Team_getRankImprovement()
{
    return this.lastYearRank - this.totalRank;
}

/**
Member method of Team for assembling the URL.
*/
function Team_url() { return poolURL + "/" + this.id; }
/**
Constructor for Team objects to initialize the variables.
*/
function Team(id, lastYearRank)
{
    this.id = id;
    this.firstHalfPoints = 0;
    this.lastYearRank = lastYearRank;
    this.totalPoints = 0;
    this.teamName = "";
    this.ptsChange = "";
    this.waiver = "";
    this.moves = "";
    this.blast = false;
    this.totalRank = "";
    this.gamesPlayedForward = "";
    this.gamesPlayedGoalie = "";
    this.gamesPlayedDefense = "";
    this.projectedPlayedForward = "";
    this.projectedPlayedGoalie = "";
    this.projectedPlayedDefense = "";
    this.ptsForward = 0;
    this.ptsGoalie = 0;
    this.ptsDefense = 0;
    this.ptsKeeper = 0;
    this.ptsNonKeeper = 0;
    this.ptsDrafted = 0;
    this.ptsOther = 0;
    this.ptsBack = 0;
    this.getSecondHalfPoints = Team_getSecondHalfPoints;
    this.getFirstHalfPoints = Team_getFirstHalfPoints;
    this.getRankImprovement = Team_getRankImprovement;
    this.url = Team_url;
}

Team.headerTitles = new Array("($) Rank", " ", "Team", "Most Improved", "1st Half", "2nd Half",  "Total", "Pts Change", "Pts Back", "Waiver", "Pts F", "Pts D", "Pts G", "GP F", "GP D", "GP G", "Moves");


var sortCol = "Total";
/**
Calls the customizeStandings(), which kicks things off.
*/
customizeStandings();


function linkStandingsTab()
{
    xpath(document, "//div[starts-with(@id, 'leaguestandingstabs')]/ul/li[1]/a")
            .snapshotItem(0).addEventListener("click",showCustomTable, false);
}

/**
 * Main function, called from above when GreaseMonkey loads the script.
 */
function customizeStandings()
{
    addRowDataToTeams();
    showCustomTable();
}

/**
 * Called from customizeStandings() after data is loaded into teams.
 * Shows the customized table.
 */
function showCustomTable()
{
 //   alert("Show Custom");
    linkStandingsTab();
   // linkAlltimeTab();
   // alert("Show Custom");
    showCustomHeader();
    showSortedRows();
}

/**
Show the rows in the standings table, sorted by the specified column.
*/
function showSortedRows(sortHeader)
{
    var standingsEm = xpath(document, "//div[starts-with(@id, 'leaguestandingstabs')]/ul/li[1]/a/span")
            .snapshotItem(0);

    if (sortHeader != null)
    {
        sortCol = sortHeader.target.innerHTML;
    }
    if (sortCol == "Total")
    {
        standingsEm.innerHTML = "Standings";
    }
    else
    {
        standingsEm.innerHTML = sortCol;
    }
    var xPathSnapshot = xpath(document, "//table[starts-with(@id, 'standingstable')]/tbody/tr");
    teams.sort(function(t1, t2)
    {
        if(sortCol == "2nd Half")
        {
            return t2.getSecondHalfPoints() - t1.getSecondHalfPoints();
        }
        else if(sortCol == "1st Half")
        {
            return t2.getFirstHalfPoints() - t1.getFirstHalfPoints();
        }
        else if (sortCol == "Most Improved")
        {
            return t2.getRankImprovement() - t1.getRankImprovement();
        }
        else if (sortCol == "Pts F")
        {
            return t2.ptsForward - t1.ptsForward;
        }
        else if (sortCol == "Pts D")
        {
            return t2.ptsDefense - t1.ptsDefense;
        }
        else if (sortCol == "Pts G")
        {
            return t2.ptsGoalie - t1.ptsGoalie;
        }
        else if (sortCol == "Non Kprs")
        {
            return t2.ptsNonKeeper - t1.ptsNonKeeper;
        }
        else if (sortCol == "Kprs")
        {
            return t2.ptsKeeper - t1.ptsKeeper;
        }
        else if (sortCol == "GP G")
        {
            return t2.gamesPlayedGoalie - t1.gamesPlayedGoalie;
        }
        else if (sortCol == "GP F")
        {
            return t2.gamesPlayedForward - t1.gamesPlayedForward;
        }
        else if (sortCol == "GP D")
        {
            return t2.gamesPlayedDefense - t1.gamesPlayedDefense;
        }

        return t2.totalPoints - t1.totalPoints;
    });

    for (var i = 0; i < xPathSnapshot.snapshotLength; i++)
    {
        showDataRow(getRank(i, sortCol), xPathSnapshot.snapshotItem(i), teams[i], sortCol);
    }

}

function getRank(teamIndex, sortCol)
{
   rank = teamIndex + 1;
   if (sortCol == 'Most Improved')
   {
        rank = 1;
        team = teams[teamIndex];
        var isLast = true;
        var numTies = 0;
        for (var i = 0; i < 12; i++)
        {
            team2 = teams[i];
            if (team2.getRankImprovement() > team.getRankImprovement())
            {
                rank++;
            }
            else if (team.getRankImprovement() > team2.getRankImprovement())
            {
                isLast=false;
            }
            else
            {
                numTies++;
            }
        }
        if (isLast)
        {
            rank = "<last>" + rank + "</last>";
        }
        return formatMoney(getMoney(rank, sortCol)/numTies) + " " + rank;
   }
   return formatMoney(getMoney(rank, sortCol)) + " " + rank;
}

function formatMoney(num)
{
    if (num < 0)
    {
        return "(-$" + formatNumber(Math.abs(num)) + ")";
    }
    else if (num == 0)
    {
        return "";
    }
    return "($" + formatNumber(num)+ ")";
}

/**
Returns the amount of money for the specified rank and sort column
*/
function getMoney(rank, sortCol)
{
    if(sortCol == 'Total')
    {
        if (rank == 1)
        {
            return 400;
        }
        if (rank == 2)
        {
            return 50;
        }
        if (rank == 3)
        {
            return 25;
        }
        if (rank == 4)
        {
            return 20;
        }
        if (rank == 5)
        {
            return 15;
        }
        if (rank == 6)
        {
            return 10;
        }
        if (rank == 7)
        {
            return 5;
        }
        if (rank == 12)
        {
            return -25;
        }
        if (rank == 11)
        {
            return -20;
        }
        if (rank == 10)
        {
            return -15;
        }
        if (rank == 9)
        {
            return -10;
        }
        if (rank == 8)
        {
            return -5;
        }
    }
    else if ((rank == 1) && (sortCol == "1st Half" || sortCol == "2nd Half"  || sortCol == "Most Improved"))
    {
        return 50;
    }

    if(sortCol == 'Most Improved')
    {
        if(rank.toString().indexOf("<last") >=0)
        {
            return -50
        }
    }



    return 0;
}

/**
Displays team data, rank and money in a specified HTMLTableRowElement.
@param rank - The row number
@param money - The amount of money for the specified row
@param row - The actual HTMLTableRowElement to use for showing the row.
@param team - The team object that contains the data to show.
*/
function showDataRow(rank,  row, team, sortCol)
{
    row.id = "standingsRow" + team.id;
    row.cells[0].innerHTML = ""
    if (team.blast)
    {
        row.cells[0].className = "first rank blast";
        var blastAnchor = document.createElement('a');
        blastAnchor.innerHTML = "";
        blastAnchor.href = team.url();
        blastAnchor.className = "blast";
        row.cells[0].appendChild(blastAnchor);
    }
    else
    {
        row.cells[0].className = "first rank";
    }
    if (rank.indexOf("-$") >= 0)
    {
        row.cells[0].className += " negative";
    }
    else if (rank.indexOf("$") >= 0)
    {
        row.cells[0].className += " positive";
    }
    row.cells[0].innerHTML += rank + ".";
    row.cells[0].style.whiteSpace = "nowrap";
    for (var i = row.cells.length -1; i >= 2; i--)
    {
        row.deleteCell(i);
    }


    var nameCell = document.createElement('td');
    nameCell.className = "team";
    var anchor = document.createElement('a');
    anchor.innerHTML = team.name;
    anchor.href = team.url();
    nameCell.appendChild(anchor);
    row.appendChild(nameCell);
    var rankImprovementCell = document.createElement('td');
    var rankImprovement = team.getRankImprovement();
    if (team.getRankImprovement() > 0)
    {
        rankImprovementCell.className = "positive";
        rankImprovement = "+" + rankImprovement;
    }
    else if (team.getRankImprovement() < 0)
    {
        rankImprovementCell.className = "negative";
    }
    rankImprovementCell.innerHTML = "<center>"+rankImprovement+"</center>";

    row.appendChild(rankImprovementCell);
    var firstHalfCell = document.createElement('td');
    firstHalfCell.innerHTML = formatNumber(team.getFirstHalfPoints());
    firstHalfCell.id="firstHalfStandings" + team.id;
    row.appendChild(firstHalfCell);
    var secondHalfCell = document.createElement('td');
    secondHalfCell.innerHTML = formatNumber(team.getSecondHalfPoints());
    row.appendChild(secondHalfCell);

    /*
    var ptsKeeperCell = document.createElement('td');
    ptsKeeperCell.id="ptsKeeper" + team.id;
    row.appendChild(ptsKeeperCell);

    var ptsNonKeeperCell = document.createElement('td');
    ptsNonKeeperCell.id="ptsNonKeeper" + team.id;
    row.appendChild(ptsNonKeeperCell);
    */
    var totalPtsCell = document.createElement('td');
    totalPtsCell.innerHTML = formatNumber(team.totalPoints);
    row.appendChild(totalPtsCell);
    var ptsChangeCell = document.createElement('td');
    ptsChangeCell.innerHTML = formatNumber(team.ptsChange);

    if (team.ptsChange < 0)
    {
        ptsChangeCell.className += " negative";
    }
    else if (team.ptsChange > 0)
    {
        ptsChangeCell.className += " positive";
    }
    ptsChangeCell.className = "positive";
    row.appendChild(ptsChangeCell);
    var ptsBack = document.createElement('td');
    ptsBack.innerHTML = formatNumber(team.ptsBack);
    ptsBack.id="ptsBack" + team.id;
    row.appendChild(ptsBack);
    var waiverCell = document.createElement('td');
    waiverCell.innerHTML = team.waiver;
    row.appendChild(waiverCell);
    var ptsFwdCell = document.createElement('td');
    ptsFwdCell.id="ptsForward" + team.id;

    row.appendChild(ptsFwdCell);
    var ptsDefCell = document.createElement('td');
    ptsDefCell.id="ptsDefense" + team.id;

    row.appendChild(ptsDefCell);
    var ptsGoalieCell = document.createElement('td');
    ptsGoalieCell.id="ptsGoalie" + team.id;

    row.appendChild(ptsGoalieCell);

    updatePositionPointsCells(team);
    var gpfCell = document.createElement('td');
    gpfCell.id="gamesPlayedForward" + team.id;
    gpfCell.innerHTML = team.gamesPlayedForward;
    gpfCell.style.whiteSpace = "nowrap";
    row.appendChild(gpfCell);
    var gpdCell = document.createElement('td');
    gpdCell.id="gamesPlayedDefense" + team.id;
    gpdCell.style.whiteSpace = "nowrap";
    row.appendChild(gpdCell);
    var gpgCell = document.createElement('td');
    gpgCell.id="gamesPlayedGoalie" + team.id;
    gpgCell.style.whiteSpace = "nowrap";
    row.appendChild(gpgCell);
    updateGamesPlayedCells(team);

    var movesCell = document.createElement('td');

    movesCell.innerHTML = team.moves;
    movesCell.className = "last";
    row.appendChild(movesCell);
    if(team.selected)
    {
        row.className = "selected";
    }
    else
    {
        row.className = null;
    }
    var background = "#F1F2ED";
    if(sortCol == "2nd Half")
    {
        secondHalfCell.style.background = background;
    }
    else if(sortCol == "1st Half")
    {
        firstHalfCell.style.background = background;
    }
    else if(sortCol == "Most Improved")
    {
        rankImprovementCell.style.background = background;
    }
    else if(sortCol == "Pts D")
    {
        ptsDefCell.style.background = background;
    }
    else if(sortCol == "Pts G")
    {
        ptsGoalieCell.style.background = background;
    }
    else if(sortCol == "Non Kprs")
    {
        ptsNonKeeperCell.style.background = background;
    }
    else if(sortCol == "Kprs")
    {
        ptsKeeperCell.style.background = background;
    }
    else if(sortCol == "Pts F")
    {
        ptsFwdCell.style.background = background;
    }
    else if(sortCol == "GP F")
    {
        gpfCell.style.background = background;
    }
    else if(sortCol == "GP D")
    {
        gpdCell.style.background = background;
    }
    else if(sortCol == "GP G")
    {
        gpgCell.style.background = background;
    }
    else
    {
        totalPtsCell.style.background = background;
    }

}

function formatNumber(num)
{
    var result = Math.round(num*Math.pow(10,2))/Math.pow(10,2);
    return ("NaN" == result + "" ) ? "-" : result;
}

/**
 * Retrieves the header tr of the standings table as an HTMLTableRowElement.
 * @return an Array of tr HTMLTableRowElement objects of the Table data.
 */
function addRowDataToTeams()
{
    var xPathSnapshot = xpath(document, "//table[starts-with(@id, 'standingstable')]/tbody/tr");
    for (var i = 0; i < xPathSnapshot.snapshotLength; i++)
    {
        addRowDataToTeam(xPathSnapshot.snapshotItem(i));
    }
    addFirstHalfStandingsToTeams();

}

/**
 * Given a row from the original table, find the Team object that corresponds
 * to the data row, and add the data from the row to the team.
 */
function addRowDataToTeam(dataRow)
{

    var anchor = xpath(dataRow, "td/a[contains(@href, '"+poolURL+"')]").snapshotItem(0);

    if(anchor.className == "blast")
    {
        anchor = xpath(dataRow, "td/a[starts-with(@href, '"+poolURL+"')]").snapshotItem(1);
    }
    var splitHref = anchor.href.split("/");
    var teamID = splitHref[splitHref.length - 1];
    var team = teams[teamID];
    team.name = anchor.innerHTML;
    var dataCells = dataRow.getElementsByTagName('td');
    if(dataCells[0].className != "first rank blast")
    {
        team.totalRank = dataCells[0].innerHTML;
    }
    else
    {
        team.totalRank = dataCells[0].innerHTML.split("</a>")[1];
        team.blast = true;
    }
    team.teamName = dataCells[2].innerHTML;
    team.totalPoints = dataCells[3].innerHTML;
    team.ptsChange = dataCells[4].innerHTML;
    team.ptsBack = dataCells[5].innerHTML;
    team.waiver = dataCells[6].innerHTML;
    team.moves = dataCells[7].innerHTML;
    if(dataRow.className == "selected")
    {
        team.selected = true;
    }
    addGamesPlayedToTeam(team);

    addPositionPointsToTeam(team);


}

/**
 * Displays the Team.headerTitles in the HTMLTableRowElement that is the table header.
 */
function showCustomHeader()
{
   var headerRow = findStandingsTableHeaderRow();
   //Delete the old header row.
   for (var i = headerRow.cells.length -1; i >= 0; i--)
   {
       headerRow.deleteCell(i);
   }
   var titles = Team.headerTitles;
   //Create the new titles for the header row.
   for (var j = 0; j < titles.length; j++)
   {
       var headerCell = document.createElement('th');

       if (titles[j] == "Rank")
       {
            headerCell.className = "first rank";
       }
       else if (titles[j] == "Team")
       {
            headerCell.className = "team";
       }
       if(j == titles.length - 1)
       {
            headerCell.className = "last";
       }
       if (titles[j] == "1st Half" || titles[j] == "2nd Half" || titles[j] == "Total" || titles[j] == "Most Improved" || titles[j] == "Pts D" || titles[j] == "Pts F" || titles[j] == "Pts G" || titles[j] == "Kprs" || titles[j] == "Non Kprs" || titles[j] == "GP D" || titles[j] == "GP F" || titles[j] == "GP G")
       {
           var anchor = document.createElement('a');
           anchor.innerHTML = titles[j];
           anchor.href = "about:";
           headerCell.appendChild(anchor);
           anchor.addEventListener('click', showSortedRows, false);
       }
       else
       {
            headerCell.innerHTML = titles[j];
       }
       headerRow.appendChild(headerCell);
   }
}
/**
 * Retrieves the team of the given index from the teams array.
 */
function getTeam(teamID)
{
    for (var i = 0; i < teams.length - 1; i++)
    {
//console.debug("i=" + i);
//console.debug("teams[i].id=" + teams[i].id + "teams[i].name" + teams[i].name);
        if (teams[i].id == teamID)
        {
            return teams[i];
        }
    }
//    alert ("Team: " + teamID + " Not Found");
    return null;
}

/**
 * Retrieves the header tr of the standings table as a HTMLTableRowElement.
 */
function findStandingsTableHeaderRow()
{
    return xpath(document, "//table[starts-with(@id, 'standingstable')]/thead/tr").snapshotItem(0);
}

/**
 * Finds an XPathResult.ORDERED_NODE_SNAPSHOT_TYPE on the given node in the DOM
 * based on the given xPathExpr.
 */
function xpath(domNode, xPathExpr)
{
    return document.evaluate(xPathExpr, domNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
}

function addFirstHalfStandingsToTeams()
{
        GM_xmlhttpRequest({
            method:"GET",
            url:"http://hockey-stats.googlecode.com/svn/temp/first_half_standings.txt",
            headers:{
                "User-Agent":"monkeyagent",
                "Accept":"text/monkey,text/xml",
                "If-Modified-Since":"Sat, 1 Jan 2000 00:00:00 GMT"
            },
            onload:function(details) {

                var s = new String(details.responseText);
                var firstHalfStandings = s.split("\n");
                for (var i = 0; i < firstHalfStandings.length; i++)
                {
                     var teamTokens = firstHalfStandings[i].split(",");
                     var team = getTeam(teamTokens[0]);
                     if (team != null)
                     {
                        team.firstHalfPoints =
                          parseFloat(teamTokens[1]);
                     }
                }
                showSortedRows();
            }
        });
}

/********************
 * Games Played stuff
 */
function addGamesPlayedToTeam(team)
{
        GM_xmlhttpRequest({
            method:"GET",
            url:"http://hockey.fantasysports.yahoo.com" + team.url(),
            headers:{
                "User-Agent":"monkeyagent",
                "Accept":"text/monkey,text/xml"
            },
            onload:function(details) {
                var s = new String(details.responseText);
                s = s.replace(/\n/g, ' ');
                var regex = "<h4>Maximum Games</h4>*.+</table>";
                var result = s.match(regex);
                var document = appendToDocument(result, "Max_Games_Table" + team.id);
                getGamesPlayedFromDiv(team);
                updateGamesPlayedCells(team);
            }
        });
}

function addPositionPointsToTeam(team)
{

        GM_xmlhttpRequest({
            method:"GET",
            url:"http://hockey.fantasysports.yahoo.com" + team.url() + "/teamlog",
            headers:{
                "User-Agent":"monkeyagent",
                "Accept":"text/monkey,text/xml"
            },
            onload:function(details) {
                var s = new String(details.responseText);
                s = s.replace(/\n/g, ' ');
                var regex = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" id=\"statTable0\" class=\"teamtable\".*</table>";
                var result = s.match(regex);
                var document = appendToDocument(result, "Position_Points_Table" + team.id);
                getPositionPointsFromLogTable(team);
                updatePositionPointsCells(team);
            }
        });
}

function getPositionPointsFromLogTable(team)
{
    var gpDivID = "Position_Points_Table" + team.id;
    var xPathPlayer = xpath(document, "id('" + gpDivID + "')/table[1]/tbody/tr/td[starts-with(@class,'player')]/div/a[starts-with(@class,'name')]");
    var xPathPos = xpath(document, "id('" + gpDivID + "')/table[1]/tbody/tr/td[starts-with(@class,'player')]/div[starts-with(@class,'detail')]/span[not(starts-with(@class,'status'))]");
    var xPathPoints = xpath(document, "id('" + gpDivID + "')/table[1]/tbody/tr/td[starts-with(@class,'stat')]");
    var xPathDetail  = xpath(document, "id('" + gpDivID + "')/table[1]/tbody/tr/td[starts-with(@class,'player')]/div[starts-with(@class,'detail')]");
    for (var i = 0, numSkaters = 0; i < xPathPos.snapshotLength; i++)
    {

        var position = xPathPos.snapshotItem(i).innerHTML;
        var points = 0;
        if (position.indexOf("- G") < 0)
        {
            numSkaters = i + 1;

  //          GM_log(xPathPlayer.snapshotItem(i).innerHTML);
  //          GM_log('g' + xPathPoints.snapshotItem((i*3) + 1).innerHTML);
  //          GM_log('a' + xPathPoints.snapshotItem((i*3) + 2).innerHTML);

            var goals =  parseInt(xPathPoints.snapshotItem((i*3) + 1).innerHTML);
            var assists = parseInt(xPathPoints.snapshotItem((i*3) + 2).innerHTML);
            if(position.indexOf("- F") >= 0)
            {
                team.ptsForward += (goals + assists);
            }
            else if(position.indexOf("- D") >= 0)
            {
                team.ptsDefense += (goals + assists);
            }
            points = goals + assists;
        }
    }
    var xPathGoalie = xpath(document, "id('" + gpDivID + "')/table[starts-with(@id,'statTable1')]/tbody/tr/td[starts-with(@class,'player')]/div/a[starts-with(@class,'name')]");
    var xPathGoaliePoints = xpath(document, "id('" + gpDivID + "')/table[starts-with(@id,'statTable1')]/tbody/tr/td[starts-with(@class,'stat')]");
    var xPathGoalieDetail  = xpath(document, "id('" + gpDivID + "')/table[starts-with(@id,'statTable1')]/tbody/tr/td[starts-with(@class,'player')]/div[starts-with(@class,'detail')]");
    for (var i = 0, numGoalies = 0; i < xPathGoalie.snapshotLength; i++)
    {
        var win = xPathGoaliePoints.snapshotItem(i * 5 + 1 ).innerHTML;
        var ga = xPathGoaliePoints.snapshotItem(i * 5 + 2 ).innerHTML;
        var sv = xPathGoaliePoints.snapshotItem(i * 5 + 3 ).innerHTML;
        var sho = xPathGoaliePoints.snapshotItem(i * 5 + 4 ).innerHTML;
        points =  (win * 1) + (sho * 2) + (sv * .04) - (ga * .25);
        team.ptsGoalie += points;
    }
}
function updatePositionPointsCells(team)
{
    var ptsForwardCell = xpath(document, "id('ptsForward" + team.id + "')").snapshotItem(0);
    var ptsDefenseCell = xpath(document, "id('ptsDefense" + team.id + "')").snapshotItem(0);
    var ptsGoalieCell = xpath(document, "id('ptsGoalie" + team.id + "')").snapshotItem(0);
   if (team.ptsForward != 0)
    {
        ptsForwardCell.innerHTML = team.ptsForward;
    }
    if (team.ptsDefense != 0)
    {
        ptsDefenseCell.innerHTML = team.ptsDefense;
    }
    if (team.ptsGoalie != 0)
    {
        ptsGoalieCell.innerHTML = formatNumber(team.ptsGoalie);
    }
}


function getGamesPlayedFromDiv(team)
{
    var gpDivID = "Max_Games_Table" + team.id
    var xPathSnapshotGP = xpath(document, "id('" + gpDivID + "')/table/tbody/tr/td[starts-with(@class,'used')]");

    team.gamesPlayedForward = xPathSnapshotGP.snapshotItem(0).innerHTML;
    team.gamesPlayedDefense = xPathSnapshotGP.snapshotItem(1).innerHTML;
    team.gamesPlayedGoalie = xPathSnapshotGP.snapshotItem(2).innerHTML;

    var xPathSnapshotProjected = xpath(document, "id('" + gpDivID + "')/table/tbody/tr/td[starts-with(@class,'projected')]");

    team.projectedPlayedForward = getProjectedGamesFromCell(xPathSnapshotProjected.snapshotItem(0).innerHTML);
    team.projectedPlayedDefense = getProjectedGamesFromCell(xPathSnapshotProjected.snapshotItem(1).innerHTML);
    team.projectedPlayedGoalie = getProjectedGamesFromCell(xPathSnapshotProjected.snapshotItem(2).innerHTML);
}

function getProjectedGamesFromCell(cellContent)
{
    cellContent = cellContent.trim();
    var regex = "^[0-9]*";
    return cellContent.match(regex);
}



function updateGamesPlayedCells(team)
{
    var gamesPlayedForwardCell = xpath(document, "id('gamesPlayedForward" + team.id + "')").snapshotItem(0);
    var gamesPlayedDefenseCell = xpath(document, "id('gamesPlayedDefense" + team.id + "')").snapshotItem(0);
    var gamesPlayedGoalieCell = xpath(document, "id('gamesPlayedGoalie" + team.id + "')").snapshotItem(0);
    updateGamesPlayedCell(gamesPlayedForwardCell, team.gamesPlayedForward, team.projectedPlayedForward, 12 * 82);
    updateGamesPlayedCell(gamesPlayedDefenseCell, team.gamesPlayedDefense, team.projectedPlayedDefense,6 * 82);
    updateGamesPlayedCell(gamesPlayedGoalieCell, team.gamesPlayedGoalie, team.projectedPlayedGoalie,1 * 82);
}

function updateGamesPlayedCell(cell, gamesPlayed, projected, maxGames)
{

    if (gamesPlayed == "")
    {
        return;
    }
    var difference = projected - maxGames;
    if (difference < 0)
    {
         cell.className= "negative";
    }
    else if (difference > 0)
    {
        cell.className= "positive";
        difference = "+" + difference;
    }
    cell.innerHTML = difference;
    cell.title="GP: " + gamesPlayed + " | Projected: " + projected + " | Max: " + maxGames;
}





/**
 Add hidden content to the DOM so we can run xpath on it
 @html   the raw html that will be part of the DOM

 @return current document
 */
function appendToDocument(html, id) {

    var div = document.getElementById(id);
    if (!div) {
        div = document.createElement("div");
        document.body.appendChild(div);
        div.id = id;
        div.style.display = 'none';
    }
    div.innerHTML = html;
    return document;
}
